import wxBaaS from '../sdk-wechat.3.23.5';
import { getPinyinFirstLetter } from '../utils/getPinyin';

// 通用的获取药膳信息函数
export async function fetchMedifood(query) {
  try {
    const medifoodInfoTable = new wxBaaS.TableObject('Medifood_case');
    const response = await medifoodInfoTable.setQuery(query).limit(100).find();
    // 获取药膳信息
    const medifoodDetails = response.data.objects;
    // 按照 Initial_letter 进行升序排序
    medifoodDetails.sort((a, b) => {
      const letterA = a.initial_letter || '';
      const letterB = b.initial_letter || '';
      // 将字母转为数字以进行排序
      return isNaN(letterA) || isNaN(letterB) 
        ? letterA.localeCompare(letterB) // 如果是非数字，按字母排序
        : Number(letterA) - Number(letterB); // 如果是数字，按数值排序
    });

    return medifoodDetails;
  } catch (error) {
    console.error('获取药膳信息失败:', error);
    throw error;
  }
}

// 获取所有药膳信息
export async function fetchAllMedifoodDetails() {
  const query = new wxBaaS.Query();
  return fetchMedifood(query);
}

// 获取需要查询的药膳信息
export async function fetchMedifoodDetails(searchConditions = [], page = 1, pageSize = 10) {
  try {
    const medifoodInfoTable = new wxBaaS.TableObject('Medifood_case');
    const query = new wxBaaS.Query();

    // 构建查询条件
    searchConditions.forEach(condition => {
      let { selectedOption, value } = condition;
      // 映射 selectedOption 到实际的数据库字段名
      switch (selectedOption) {
        case '药膳名称':
          selectedOption = 'name';
          break;
        case '药膳类型':
          selectedOption = 'Medifood_classify';
          break;
        case '药膳颜色':
          selectedOption = 'Medifood_color';
          break;
        case '适应症':
          selectedOption = 'indication';
          break;
        case '吃法':
          selectedOption = 'Edible_method';
          break;
        case '治疗部位':
          selectedOption = 'treatment_site';
          break;
      }

      if (value) {
        query.contains(selectedOption, value);
      }
    });

    // 使用 limit 和 offset 方法进行分页
    const start = (page - 1) * pageSize;
    const response = await medifoodInfoTable.setQuery(query).limit(pageSize).offset(start).find();
    
    return response.data.objects;
  } catch (error) {
    console.error('获取药膳信息失败:', error);
    throw error;
  }
}
// 根据id获取药膳信息
export async function fetchDetailById(id) {
  try {
    const medifoodInfoTable = new wxBaaS.TableObject('Medifood_case');
    const response = await medifoodInfoTable.get(id); // 使用 get 方法获取指定 ID 的药膳信息
    return response.data;
  } catch (error) {
    console.error('获取药膳详细信息失败:', error);
    throw error;
  }
}
export async function checkIfCollected(userId, caseId) {
  const MyTableObject = new wx.BaaS.TableObject('case_collection');
  const query = new wx.BaaS.Query();
  query.compare('user_id', '=', userId);
  query.compare('case_id', '=', caseId);
  const records = await MyTableObject.setQuery(query).find();

  return records.data.objects.length > 0;
}

// 根据用户的id获取药膳信息
export async function fetchDetailByCreat(created_by) {
  try {
    const medifoodInfoTable = new wxBaaS.TableObject('Medifood_case');
    const query = new wxBaaS.Query();
    query.compare('created_by', '=', created_by); // 查询条件
    const response = await medifoodInfoTable.setQuery(query).find(); // 使用 find 方法获取符合条件的药膳信息
    return response.data.objects;
  } catch (error) {
    console.error('获取药膳详细信息失败:', error);
    throw error;
  }
}

// 添加药膳信息
export async function addMedifoodInfo(medifoodData) {
  try {
    const firstLetter = await getPinyinFirstLetter(medifoodData.name);
    medifoodData.initial_letter = firstLetter;
    const medifoodInfoTable = new wxBaaS.TableObject('Medifood_case');
    const newMedifoodInfo = medifoodInfoTable.create();
    Object.keys(medifoodData).forEach(key => newMedifoodInfo.set(key, medifoodData[key]));
    const response = await newMedifoodInfo.save();
    return response.data.id;
  } catch (error) {
    console.error('添加药膳信息失败:', error);
    throw error;
  }
}

// 更新药膳信息
export async function updateMedifoodInfo(infoId, updateData) {
  try {
     // 检查是否需要更新首字母
     const firstLetter = await getPinyinFirstLetter(updateData.name);
     if (updateData.initial_letter !== firstLetter) {
       updateData.initial_letter = firstLetter;
     }
    const medifoodInfoTable = new wxBaaS.TableObject('Medifood_case');
    const medifoodInfoToUpdate = medifoodInfoTable.getWithoutData(infoId);
    Object.keys(updateData).forEach(key => medifoodInfoToUpdate.set(key, updateData[key]));
    await medifoodInfoToUpdate.update();
    return true;
  } catch (error) {
    console.error('更新药膳信息失败:', error);
    throw error;
  }
}

  // 删除药膳信息
export async function deleteMedifoodInfo(infoId) {
  try {
    const response = await wx.BaaS.deleteRecord({
      tableID: 'Medifood_case',
      recordID: infoId,
    });
    return true;
  } catch (error) {
    console.error('删除药膳信息失败:', error);
    throw error;
  }
}

